<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     Pagizer
 * @subpackage  backoffice
 */

class m_backoffice_services_RootNodeService extends f_core_Service
{
	/**
	 * @var m_backoffice_services_RootNodeService
	 */
	private static $instance;
	
	/**
	 * Constructor
	 */
	private function __construct()
	{
		// Code if needed...
	}
	
	/**
	 * @return m_backoffice_services_RootNodeService
	 */
	public static function getInstance()
	{
		if (self::$instance === null)
		{
			self::$instance = new self();
		}
		return self::$instance;
	}
	
	/**
	 * Create a new root node for a new module tree
	 * @param $moduleName
	 * @param $lang
	 * @return m_backoffice_documents_RootNode
	 */
	public function createModuleRootNode($moduleName, $lang = null)
	{
		if(is_null($lang)) $lang = $this->getContextLang();
		
		$root = $this->getModuleRootNode($moduleName, $lang);
		
		if(is_null($root))
		{
			$rootNode = m_backoffice_documents_RootNode::createNew();
			$rootNode->setAuthor("pagizer")->setLabel(ucfirst($moduleName)." root node")->setLang($lang)->setModule($moduleName)->save();
			return $rootNode;
		}
		
		return $root;
	}
	
	/**
	 * Get tree root node for a given module name
	 * @param $moduleName
	 * @param $lang
	 * @return m_backoffice_documents_RootNode
	 */
	public function getModuleRootNode($moduleName, $lang = null)
	{
		if(is_null($lang)) $lang = $this->getContextLang();

        $file = MODULES_DIR.DIRECTORY_SEPARATOR.$moduleName.DIRECTORY_SEPARATOR."config".DIRECTORY_SEPARATOR."treeParser.xml";

        $mName = f_xml_Xpath::getInstance($file)->fromXpath("rootNode")->getAttributeValue('rootnode');

        if(!is_null($mName))
        {
            $rootNode = $this->getDocumentProvider()->loadDocuments("modules_backoffice/rootNode")->whereIsEqual("module", $mName)->retrieveFirstDocument($lang);
            $rootNode->setModule($moduleName);
        }
        else
        {
            $rootNode = $this->getDocumentProvider()->loadDocuments("modules_backoffice/rootNode")->whereIsEqual("module", $moduleName)->retrieveFirstDocument($lang);
        }

		return $rootNode;
	}
}